#include "Task/include/led_task.h"

#include "sys.h"
#include "HAL_gpio.h"

#include "FreeRTOS.h"
#include "task.h"

#define LED_TASK_NAME "led"
#define LED_TASK_PRIORIY (tskIDLE_PRIORITY + 3)
#define LED_TASK_STACK_SIZE (configMINIMAL_STACK_SIZE)

typedef struct
{
    StaticTask_t _task_buffer;
    StackType_t  _stack_buffer[LED_TASK_STACK_SIZE];
    TaskHandle_t task_id;
} led_task_t;

static led_task_t gs_led_task = {0};

static void led_task_gpio_init(void)
{
    GPIO_InitTypeDef init = {0};

    init.GPIO_Pin   = GPIO_Pin_8;
    init.GPIO_Mode  = GPIO_Mode_Out_PP;
    init.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOD, &init);
}

static void led_task_main(void *param)
{
    uint32_t led = 0;

    led_task_gpio_init();

    while (1)
    {
        led ^= 1;
        if (led)
            GPIO_WriteBit(GPIOD, GPIO_Pin_8, Bit_SET);
        else
            GPIO_WriteBit(GPIOD, GPIO_Pin_8, Bit_RESET);

        vTaskDelay(1000);
    }
}

uint32_t led_task_init(void)
{
    BaseType_t ret;

    if (gs_led_task.task_id != NULL)
        return 1;

    ret = xTaskCreateStatic(led_task_main, LED_TASK_NAME,
        LED_TASK_STACK_SIZE, NULL, LED_TASK_PRIORIY,
        &gs_led_task.task_id,
        gs_led_task._stack_buffer, &gs_led_task._task_buffer);
    
    return (ret == pdTRUE) ? 0 : 1;
}
